package com.tz.colawallet.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tz.colawallet.R;
import com.tz.colawallet.basecode.base.BaseActivity;
import com.tz.colawallet.basecode.util.MyStringUtils;
import com.tz.colawallet.basecode.util.SysUtils;
import com.tz.colawallet.bean.GetTags;
import com.tz.colawallet.ui.adapter.PerfectMessageAdapter;
import com.tz.colawallet.ui.biz.PerfectMessageBiz;
import com.tz.colawallet.ui.component.DaggerPerfectMessageComponent;
import com.tz.colawallet.ui.contract.PerfectMessageContract;
import com.tz.colawallet.ui.module.PerfectMessageModule;
import com.tz.colawallet.ui.presenter.PerfectMessagePresenter;
import com.tz.colawallet.util.AlertUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class PerfectMessageActivity extends BaseActivity implements PerfectMessageContract.View {
    @Inject
    PerfectMessagePresenter presenter;
    @Inject
    PerfectMessageBiz biz;

    EditText perfectName;
    TextView perfectSex;
    TextView perfectBirthday;
    EditText perfectMoney;
    TextView perfectLocation;
    LinearLayout reloadLocation;
    ImageView agreeImg1;
    TextView agreeText;
    ImageView agreeImg2;
    Button perfectSubmit;
    RecyclerView recyclerView;

    private boolean chooseAgreeImg1 = true, chooseAgreeImg2 = true;
    private int chooseSex = 0;//男0女1
    private AlertDialog alertDialog2; //单选框

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();

    private PerfectMessageAdapter perfectMessageAdapter;
    private List<GetTags> getTagsList;
    private String mCity = "";

    @Override
    protected void setup() {
        super.setup();
        DaggerPerfectMessageComponent.builder().perfectMessageModule(new PerfectMessageModule(this)).build().inject(this);
        presenter.setBiz(biz);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_perfect_message;
    }

    @Override
    protected void init() {
        perfectName = findViewById(R.id.perfect_name);
        perfectSex = findViewById(R.id.perfect_sex);
        perfectBirthday = findViewById(R.id.perfect_birthday);
        perfectMoney = findViewById(R.id.perfect_money);
        perfectLocation = findViewById(R.id.perfect_location);
        reloadLocation = findViewById(R.id.reload_location);
        agreeImg1 = findViewById(R.id.agree_img1);
        agreeText = findViewById(R.id.agree_text);
        agreeImg2 = findViewById(R.id.agree_img2);
        perfectSubmit = findViewById(R.id.perfect_submit);
        recyclerView = findViewById(R.id.perfect_recycler);

        //开启百度定位
        baiduLocation();
        presenter.getTags();

        getTagsList = new ArrayList<>();
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        perfectMessageAdapter = new PerfectMessageAdapter(R.layout.item_per_msg, this);
        recyclerView.setAdapter(perfectMessageAdapter);

        perfectMessageAdapter.setOnListener(new PerfectMessageAdapter.OnListener() {
            @Override
            public void onListener(int position) {
                if (getTagsList.get(position).isChoose()) {
                    getTagsList.get(position).setChoose(false);
                } else {
                    getTagsList.get(position).setChoose(true);
                }
                perfectMessageAdapter.notifyDataSetChanged();
            }
        });

        perfectSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSingleAlertDialog();
            }
        });
        perfectBirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerDialog timePickerDialog = AlertUtils.timePicker2(PerfectMessageActivity.this, "出生日期", new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        perfectBirthday.setText(SysUtils.sfBirthday.format(new Date(millseconds)));
                    }
                });
                timePickerDialog.show(getSupportFragmentManager(), "all");
            }
        });

        reloadLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开启百度定位
                baiduLocation();
            }
        });

        agreeImg1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chooseAgreeImg1) {
                    chooseAgreeImg1 = false;
                    agreeImg1.setBackgroundResource(R.drawable.shape_stroke_frame_red);
                } else {
                    chooseAgreeImg1 = true;
                    agreeImg1.setBackgroundResource(R.drawable.shape_stroke_frame_gray);
                }
            }
        });
        agreeImg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chooseAgreeImg2) {
                    chooseAgreeImg2 = false;
                    agreeImg2.setBackgroundResource(R.drawable.shape_stroke_frame_red);
                } else {
                    chooseAgreeImg2 = true;
                    agreeImg2.setBackgroundResource(R.drawable.shape_stroke_frame_gray);
                }
            }
        });
        agreeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchActivity(UserAgreementActivity.class, null);
            }
        });
        perfectSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (perfectName.getText().toString().isEmpty()) {
                    showToast("请输入中文姓名");
                    return;
                }
                if (perfectSex.getText().toString().isEmpty()) {
                    showToast("请选择姓名");
                    return;
                }
                if (perfectBirthday.getText().toString().isEmpty()) {
                    showToast("请选择出生日期");
                    return;
                }
                if (perfectMoney.getText().toString().isEmpty()) {
                    showToast("输入贷款金额");
                    return;
                }
                if (mCity.isEmpty()) {
                    showToast("请开启定位重新定位");
                    baiduLocation();
                    return;
                }

                String tagIds = "";
                for (GetTags getTags : getTagsList) {
                    if (getTags.isChoose()) {
                        tagIds = tagIds + getTags.getId() + ",";
                    }
                }

                if (tagIds.isEmpty()) {
                    showToast("请选择资产信息");
                    return;
                }

                presenter.detail(perfectName.getText().toString(), chooseSex, perfectBirthday.getText().toString(),
                        perfectMoney.getText().toString(), tagIds, mCity);
            }
        });
    }

    @Override
    protected void initTitle() {

    }

    public void showSingleAlertDialog() {
        final String[] items = {"男", "女"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle("这是单选框");
        alertBuilder.setSingleChoiceItems(items, chooseSex, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                chooseSex = i;
            }
        });

        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog2.dismiss();
                perfectSex.setText(items[chooseSex]);
            }
        });

        alertBuilder.setNegativeButton("取消", null);

        alertDialog2 = alertBuilder.create();
        alertDialog2.show();
    }

    @Override
    public Context curContext() {
        return this;
    }

    @Override
    public void showTags(List<GetTags> o) {
        getTagsList.addAll(o);
        perfectMessageAdapter.replaceData(getTagsList);
    }

    @Override
    public void showDetail() {
        showToast("提交信息成功");
        finish();
    }

    //定位-------------------------------------------------------------------------

    @SuppressLint("CheckResult")
    private void baiduLocation() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
//                , Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            mLocationClient = new LocationClient(getApplicationContext());
                            //声明LocationClient类
                            mLocationClient.registerLocationListener(myListener);

                            LocationClientOption option = new LocationClientOption();
                            option.setIsNeedAddress(true);
                            mLocationClient.setLocOption(option);
//                            initLocation();

                            mLocationClient.start();
                            mLocationClient.requestLocation();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


//        RxPermissions rxPermissions = new RxPermissions(this);
//        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
////                , Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
//        )
//                .subscribe(granted -> {
//                    if (granted) {
//                        //声明LocationClient类
//                        mLocationClient = new LocationClient(getApplicationContext());
//                        //注册监听函数
//                        mLocationClient.registerLocationListener(myListener);
//                        initLocation();
//
//                        mLocationClient.start();
//                        mLocationClient.requestLocation();
//                    } else {
//                        // At least one permission is denied
//                    }
//                });

    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps
        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息

            System.out.println("province==:" + province);
            System.out.println("city==:" + city);
            System.out.println("district==:" + district);
            if (!MyStringUtils.isEmpty(city)) {
                city = city.substring(0, city.length() - 1);
                mCity = city;
                perfectLocation.setText("当前定位：" + city);
                showToast("定位成功");
//                    SPUtils.put(HomeActivity.this, Key.PER_LOCATION_CITY, city);
            } else {
                showToast("正在定位中");
//                    perfectLocation.setText("当前定位：暂无");
            }
        }
    }


}
